package elastic.learn.transport.search;


import elastic.learn.transport.ElasticsearchConfig;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.util.Date;

public class ScrollSearch {
    public static void main(String[] args) {
        TransportClient client = ElasticsearchConfig.getElasticsearchClient();
        QueryBuilder qb = QueryBuilders.termQuery("gender", "male");

        SearchResponse scrollResp = client.prepareSearch("index")
                .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)
                .setScroll(new TimeValue(60000))
                .setQuery(qb)
                .setSize(2 ).get(); //max of 100 hits will be returned for each scroll
//Scroll until no hits are returned
        do {
            System.out.println("新一次循环" + new Date());
            for (SearchHit hit : scrollResp.getHits().getHits()) {
                System.out.println(hit.getSourceAsMap());
            }

            scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
        }
        while (scrollResp.getHits().getHits().length != 0); // Zero hits mark the end of the scroll and the while loop.
    }
}
